<template>
  <div>
    <cj-popup v-model="showAddAreaModal" round class="bpm c-w80">
      <div class="c-pt60 c-pb40">
        <img :src="$addXossFilter(require('../../assets/add_addr.png'))" class="c-ww176 c-mlr-auto" alt="" />
        <div class="c-fs28 c-fw400 c-mt40 c-fc-xblack c-textAlign-c">请填写您的所在地区</div>
        <div class="c-fs24 c-fc-gray c-mt16 c-mh40 c-bd-b1 c-pb20">方便我们为您提供更多优质、准确、便捷的服务。</div>
        <div class="c-flex-row c-aligni-center c-pv26 c-bd-b1 c-p c-mh40 c-ph10 c-p">
          <div v-if="isWeiXin && isOpenGetLocation" @click="getLocation" class="c-w100 c-h c-flex-row c-aligni-center c-justify-sb">
            <span class="c-fs24 c-lh34 c-fc-gray">所在地</span>
            <div v-if="!(addrValue && addrValue.length)" class="c-fs24 c-lh34 c-fc-sgray">
              <span>请点击定位</span>
              <span class="c-fs24 iconfont c-fc-sgray c-ml10">&#xe905;</span>
            </div>
            <div v-else class="c-fs24 c-lh34 c-fc-gray">
              <span>{{getAddressName(addrValue)}}</span>
              <span class="c-fs24 iconfont c-fc-sgray c-ml10">&#xe905;</span>
            </div>
          </div>
          <template v-if="!isWeiXin || !isOpenGetLocation">
            <x-address :themeColor="$getThemeColor()" :show.sync="showAddress" v-model="addrValue" @on-hide="saveAddress" title="" :value-text-align="'left'" :list="addressData" placeholder="所在地" class="c-flex-grow1 c-fs24 bpm"></x-address>
            <span class="c-pa c-p-t0 c-p-r0 iconfont c-fs20 c-fc-sgray c-p-t36 c-pz-1">&#xe908;</span>
          </template>
          <!-- <div class="errorTipText">{{isWeiXin && !isOpenGetLocation ? '请先把手机"设置-微信定位"开启' : ''}}</div> -->
        </div>
        <div @click="submit" v-if="isNeed" :class="addrValue.length == 0 ? 'c-bg-f2' : 'theme-bg'" class="c-fc-white c-lh c-fs24 c-hh60 c-flex-row c-flex-center c-br40 c-mh40 c-mt40">确定</div>
        <div v-else class="c-flex-row c-aligni-center c-justify-sb c-ph40 c-mt40">
          <div @click="ignore" class="c-bd1-F1F1F5 c-fs24 c-fc-xblack c-hh60 c-flex-row c-flex-center c-br40 c-w0 c-flex-grow1 c-lh">忽略</div>
          <div class="c-ww40 c-hh20"></div>
          <div @click="submit" :class="addrValue.length == 0 ? 'c-bg-f2' : 'theme-bg'" class="c-fs24 c-hh60 c-flex-row c-flex-center c-br40 c-w0 c-flex-grow1 c-lh c-fc-white">确定</div>
        </div>
      </div>
    </cj-popup>
  </div>
</template>

<script>
import {XAddress } from 'ckjrweb-mp-ui/src/components/index';
import { loadBMap } from "@/utils/loadBMap.js"
import { utilJs, wxUtilJs } from "@/utils/common.js";
export default {
  name: "addAreaModal",
  components: {
    XAddress
  },
  props: {
    showAddAreaModal: {
      type: Boolean,
      default: false
    },
    isNeed: {
      type: Boolean,
      default: false
    }
  },
  beforeCreate() { },
  data() {
    return {
      addrValue: [],
      addressData: [],
      isSubmit: true, //防止多次提交
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      isOpenGetLocation: true, // 是否开启定位
      isWeiXin: true,
      showAddress: false,
    };
  },
  mounted() {
    this.isWeiXin = utilJs.isWeiXin();
  },
  computed: {
    isNeedFillArea() { // 是否需要必填用户地区（旧版和新版区域代理都需要）, 私人订制,enableShareholderAreaAgent股东区域代理必填地区
      return this.enableAreaAgent == 1 || (this.companyAuth && this.companyAuth.enableNewAreaAgent == 1) || this.companyId == "ww67ok" || (this.companyAuth && this.companyAuth.enableShareholderAreaAgent == 1)
    },
  },
  watch: {
  },
  methods: {
    ignore() {
      this.$emit('ignoreArea');
    },
    getAddressName(addrValue) {
      let provinceStr = '', cityStr = '', areaStr = '';
      this.addressData && this.addressData.forEach(item => {
        if (item.value == addrValue[0]) {
          provinceStr = item.name
        }
        if (item.value == addrValue[1]) {
          cityStr = item.name
        }
        if (item.value == addrValue[2]) {
          areaStr = item.name
        }
      })
      return provinceStr + ' ' + cityStr + ' ' + areaStr
    },
    getAddId(list, id) {
      if (list && list.length == 1) {
        return list[0].value
      }
      let currentId = ''
      list.forEach((item) => {
        if (item.parent == id) {
          currentId = item.value
        }
      })
      return currentId
    },
    getAddressId(addComp) {
      let provinceId = '', cityIds = [], cityId = '', areaIds = [], areaId = ''
      this.addressData && this.addressData.forEach(item => {
        item.name = ['北京', '天津', '上海', '重庆'].includes(item.name) ? (item.name + '市') : item.name
        if (item.name == addComp.province && item.level == 1) {
          provinceId = item.value
        }
        if (item.name == addComp.city && item.level == 2) { // 防止市名重复
          cityIds.push(item)
        }
        if (item.name == addComp.district && item.level == 3) { // 防止区名重复
          areaIds.push(item)
        }
      })
      cityId = this.getAddId(cityIds, provinceId)
      areaId = this.getAddId(areaIds, cityId)
      this.addrValue = ['' + provinceId, '' + cityId, '' + areaId]
      // 如果定位获取到的数据不完整，就自动弹出选择框
      if (!(this.addrValue && this.addrValue.length == 3 && provinceId && cityId && areaId)) {
        this.addrValue = []
        this.isOpenGetLocation = false
        this.$nextTick(() => {
          this.showAddress = true
        })
        return
      }
      this.saveAddress(this.addrValue)
    },
    getLocation() {
      if (!this.isWeiXin) {
        return
      }
      let that = this;
      wxUtilJs.getLocation().then((res) => {
        that.getBdAddress(res.longitude, res.latitude);
        that.isOpenGetLocation = true;
      }, (failRes) => {
        that.isOpenGetLocation = false
        that.$nextTick(() => {
          that.showAddress = true
        })
        console.log('获取经纬度失败');
      });
    },
    getBdAddress(longitude, latitude) {
      /* eslint-disable */
      let that = this;
      that.$loading.hide();
      that.$loading.show({
        text: "定位中"
      });
      loadBMap().then(BMap => {
        let point = new BMap.Point(longitude, latitude)
        let gc = new BMap.Geocoder()
        gc.getLocation(point, function(rs){
          that.$loading.hide();
          const addComp = rs.addressComponents
          // 可以通过addComp对象获取到省、市、县、区、街道多少号等信息
          that.getAddressId(addComp)
        })
      })
    },
    saveAddress(closeType) {
      if (closeType && this.addrValue.length == 0) {
        this.$showCjToast({
          text: "请选择地址",
          type: 'warn',
        });
      }
    },
    getAreaListForAgent() {
      utilJs.getMethod(`${global.apiurl}common/getAreaListForAgent`, res => {
        this.addressData = res.data;
      }, failRes => {});
    },
    //检测提交
    checkSubmit() {
      let msg = '';
      // 判断必填所在地是否都填了
      if (this.addrValue.length == 0) {
        msg = "请选择所在地";
      }
      if (!!msg) {
        this.$showCjToast({
          text: msg,
          type: "warn",
        });
        return false;
      } else {
        return true;
      }
    },
    submit: function () {
      if (this.addrValue.length == 0) {
        return;
      }
      if (!this.isSubmit) {
        return;
      }
      this.isSubmit = false;
      let postData = {
        provinceId: this.addrValue[0],
        cityId: this.addrValue[1],
        areaId: this.addrValue[2]
      }
      utilJs.postMethod(`${global.apiurl}members/saveUserArea`, postData, res => {
        this.isSubmit = true;
        this.$showCjToast({
          text: "设置成功",
          type: "success",
        });
        this.$emit('closeAddArea')
      }, function () {
        this.isSubmit = true;
      });
    },
  },
  activated() {
  },
  deactivated() {
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.vux-cell-box:not(:first-child):before {
  border-top: none !important;
}
.bpm .weui-mask {
  z-index: 10001 !important;
}
.bpm .weui-dialog {
  z-index: 40000 !important;
  max-width: 16rem;
  border-radius: 0.5rem;
}
.maxh380 {
  max-height: 9.5rem;
}
.bpm .vux-cell-placeholder {
  color: #ccc !important;
}
.bpm .vux-cell-value {
  color: #333 !important;
}
.errorTipText {
  font-weight: 400;
  font-size: 0.45rem;
  color: #ff300c;
  line-height: 0.65rem;
  position: absolute;
  right: 0;
  bottom: 0;
}
.c-bd1-F1F1F5 {
  border: 1px solid #f1f1f5;
}
</style>
